<template>
    <div class="boxs">
        <el-card>
            <el-form :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item label="包名 ">
                    <el-select v-model="queryParams.pk" @change="handleQuery">
                        <el-option v-for="item in pkList" :key="item.pk" :label="item.shortName"
                            :value="item.pk"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="处理状态">
                    <el-select v-model="queryParams.is_agree" @change="handleQuery">
                        <el-option v-for="item in is_agreetList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="起止时间">
                    <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                        :start-placeholder="$t('table.start')" :end-placeholder="$t('table.end')" @change="timeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="small"
                        @click="handleQuery">{{ $t('table.search') }}</el-button>
                    <el-button icon="el-icon-refresh" size="small"
                        @click="resetQuery">{{ $t('table.reset') }}</el-button>

                </el-form-item>
            </el-form>
            <div class="flex_between">
                <div v-if="totalUSD!=0" style=" font-size: 14px;color:red;font-weight: bold;">
                    已退:≈${{ totalUSD }}</div>
                <!-- <el-button type="warning" icon="el-icon-download" size="small"
                    @click="handleExport">{{ $t('table.export') }}</el-button> -->
            </div>
            <el-table border :data="moreArr" style="margin-top: 15px" v-loading="loading">
                <el-table-column label="index" align="center" width="60" type="index" />
                <el-table-column label="包名" align="center" prop="pk_str" />
                <el-table-column label="退款原因" align="center" prop="consumption_request_reason_str" />
                <el-table-column label="是否回复" align="center" width="150" prop="state">
                    <template slot-scope="scope">
                        <el-tag type="danger" v-if="scope.row.is_reply == '0'">否</el-tag>

                        <el-tag type="success" v-if="scope.row.is_reply == '1'">是</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="处理状态" align="center" width="150" prop="state">
                    <template slot-scope="scope">
                        <el-tag type="primary" v-if="scope.row.is_agree == '0'">审核中</el-tag>
                        <el-tag type="danger" v-if="scope.row.is_agree == '1'">拒绝退款</el-tag>

                        <el-tag type="success" v-if="scope.row.is_agree == '2'">同意退款</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="续订价格" align="center" prop="price" />
                <el-table-column label="产品" align="center" prop="product_id" />
                <el-table-column label="地区代码" align="center" prop="storefront" />
                <el-table-column label="申请时间" align="center" prop="create_date" />
                <el-table-column label="更新时间" align="center" prop="update_date" />
                <el-table-column :label="$t('feedback.operate')" align="center" width="100">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">history</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.size"
                @pagination="getMore" />
        </el-card>

        <el-dialog :title="$t('feedback.operate')" :visible.sync="dialogVisible" width="1000px">
            <el-table border :data="refundList" style="margin-top: 15px" v-loading="loading">
                <el-table-column label="通知类型" align="center" prop="notification_type_str" />
                <el-table-column label="子类" align="center" prop="subtype_str" />
                <el-table-column label="优惠折扣类型" align="center" prop="offer_discount_type_str" />
                <el-table-column label="续订价格" align="center" prop="price" />
                <el-table-column label="产品" align="center" prop="product_id" />
                <el-table-column label="地区代码" align="center" prop="storefront" />
                <el-table-column label="更新时间" align="center" prop="update_date" />
            </el-table>
        </el-dialog>
    </div>
</template>
<script>
import { getStorefrontList, getDataListAll, getRefundByPkgName, getHistoryList, getPkList, getRefundByPkgNameUSD } from "@/api/refund";
import * as XLSX from "xlsx";

export default {
    name: "notificationList",
    data() {
        return {
            totalUSD:0,
            refundList: [],
            languageContent: '',
            goalLanguage: "zh_CN",
            languageList: [],
            translateLoading: false,
            pkList: [],
            is_agreetList: [
                {
                    id: "0",
                    name: "审核中",
                },
                {
                    id: "1",
                    name: "拒绝退款",
                },
                {
                    id: "2",
                    name: "同意退款",
                },
            ],
            queryParams: {
                page: 1,
                size: 10,
                dateRange: {
                    start: "",
                    end: "",
                },
                dateRange2: {
                    start: "",
                    end: "",
                },
                dateRange3: {
                    start: "",
                    end: "",
                },
                state: "",
                pk: "",
                is_agree: "",
            },
            total: 0,
            loading: false,
            addLoading: false,
            moreArr: [],
            dialogVisible: false,
            form: {
                comment_type: "",
            },
            search: "",
            rules: {
                comment_type: [
                    { required: true, message: "请输入类型", trigger: "blur" },
                ],
            },
            value1: "",
            value2: "",
            value3: "",
            notificationTypeList: [
                { name: '订阅自动续订', id: 'SUBSCRIBED' },
                { name: '退款请求', id: 'CONSUMPTION_REQUEST' },
                { name: '订阅计划更改', id: 'DID_CHANGE_RENEWAL_PREF' },
                { name: '订单重试', id: 'DID_FAIL_TO_RENEW' },
                { name: '用户订阅了自动续订', id: 'SUBSCRIBED' },
                { name: '成功续订', id: 'DID_RENEW' },
                { name: '订阅过期', id: 'EXPIRED' },
                { name: '成功退款', id: 'REFUND' },
                { name: 'App Store 拒绝了用户退款请求', id: 'REFUND_DECLINED' },
                { name: 'App Store 撤销退款', id: 'REFUND_REVERSED' },
            ],
            offerDiscountTypeList: [
                { id: 1, name: '是' },
                { id: 2, name: '否' }
            ],
            storefrontList: [],
            subtypeList: [
                { name: '用户首次订阅成功', id: 'INITIAL_BUY' },
                { name: '用户禁用了订阅自动续订，或者用户申请退款后 App Store 禁用了订阅自动续订', id: 'AUTO_RENEW_DISABLED' },
                { name: '用户已启用订阅自动续订', id: 'AUTO_RENEW_ENABLED' },
                { name: '之前续订失败的已过期订阅已成功续订', id: 'BILLING_RECOVERY' },
                { name: '订阅已过期，因为订阅在计费重试期结束之前未能续订', id: 'BILLING_RETRY' },
                { name: '由于账单问题，订阅续订失败', id: 'GRACE_PERIOD' },
                { name: '用户已升级其订阅或跨级升级到具有相同期限的订阅', id: 'UPGRADE' },
                { name: '用户禁用订阅自动续订后订阅已过期', id: 'VOLUNTARY' },
                { name: '用户已降级其订阅或跨级订阅，降级将在下一个续订日期生效。', id: 'DOWNGRADE' },
            ],
        };
    },
    created() {
        const { pk } = this.$route.query;
        this.queryParams.pk = pk
        this.getMore();
        this.getStorefrontList();
        this.getPkList()
    },
    methods: {
     
        async handleExport() {
            this.loading = true;
            let { data } = await getDataListAll(this.queryParams);
            const headers = {
                pk: '包名',
                notification_type: '通知类型',
                subtype: '子类',
                offer_discount_type: '优惠折扣类型',
                price: '续订价格',
                product_id: '产品',
                storefront: '地区代码',
                auto_renew_status: '自动续订',
                expiration_intent: '订阅过期原因',
                original_purchase_date: '首次购买时间',
                renewal_date: '订阅到期时间',
                renewal_price: '下期续订价格',
                update_date: '更新时间',
            };
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in item) {
                    if (headers[key]) {
                        newItem[headers[key]] = item[key];
                    } else {
                        newItem[key] = item[key];
                    }
                }
                return newItem;
            });
            const ws = XLSX.utils.json_to_sheet(transformedData); // 将JSON转换成sheet
            const wb = XLSX.utils.book_new(); // 新建workbook
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 在workbook中添加新的sheet
            XLSX.writeFile(wb, "MySpreadsheet.xlsx"); // 写文件并触发下载
            this.loading = false;
        },
        timeChange() {
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];
            this.handleQuery();
        },
        timeChange2() {
            this.queryParams.dateRange2.start = this.value2[0];
            this.queryParams.dateRange2.end = this.value2[1];
            this.handleQuery();
        },
        timeChange3() {
            this.queryParams.dateRange3.start = this.value3[0];
            this.queryParams.dateRange3.end = this.value3[1];
            this.handleQuery();
        },
        getKeyByValue(object, value) {
            return Object.keys(object).find((key) => object[key] === value);
        },
        async getPkList() {
            let { data } = await getPkList();
            this.pkList = data
        },
        async getStorefrontList() {
            let { data } = await getStorefrontList();
            this.storefrontList = data
        },
        async getMore() {
            this.loading = true;
            let { data, total } = await getRefundByPkgName(this.queryParams);
            let { totalUSD } = await getRefundByPkgNameUSD(this.queryParams);
            this.loading = false;
            this.totalUSD = totalUSD
            data.forEach(element => {
                // 处理 notification_type
                switch (element.notification_type) {
                    case 'SUBSCRIBED':
                        element.notification_type_str = '用户订阅了自动续订';
                        break;
                    case 'CONSUMPTION_REQUEST':
                        element.notification_type_str = '用户发起退款请求';
                        break;
                    case 'DID_CHANGE_RENEWAL_PREF':
                    case 'DID_CHANGE_RENEWAL_STATUS':
                        element.notification_type_str = '用户对订阅计划进行了更改';
                        break;
                    case 'DID_FAIL_TO_RENEW':
                        element.notification_type_str = '用户因账单问题而无法续订，订阅进入账单重试期。';
                        break;
                    case 'DID_RENEW':
                        element.notification_type_str = '用户订阅已成功续订';
                        break;
                    case 'EXPIRED':
                        element.notification_type_str = '用户订阅已过期';
                        break;
                    case 'REFUND':
                        element.notification_type_str = '已成功退款';
                        break;
                    case 'REFUND_DECLINED':
                        element.notification_type_str = 'App Store 拒绝了用户退款请求';
                        break;
                    case 'REFUND_REVERSED':
                        element.notification_type_str = 'App Store 因客户提出的争议而撤销了之前批准的退款';
                        break;
                }
                switch (element.pk) {
                    case 'com.seamobitech.BeautyAI':
                        element.pk_str = 'BeautyAI';
                        break;
                    case 'com.seamobitech.QRCodeReadAndGenerate':
                        element.pk_str = 'iosQr';
                        break;
                    case 'com.seamobitech.whatsscanwebclone':
                        element.pk_str = 'iosWa';
                        break;
                    case 'com.seamobitech.UniversalTVRemoteControl':
                        element.pk_str = 'universal';
                        break;
                    case 'com.seamobitech.roku':
                        element.pk_str = 'iosRoku';
                        break;
                    case 'com.seamobitech.HeartPulse':
                        element.pk_str = 'iosHeartPulse';
                        break;
                }
                // 处理 subtype
                switch (element.subtype) {
                    case 'INITIAL_BUY':
                        element.subtype_str = '用户首次订阅成功';
                        break;
                    case 'AUTO_RENEW_DISABLED':
                        element.subtype_str = '用户禁用了订阅自动续订，或者用户申请退款后 App Store 禁用了订阅自动续订';
                        break;
                    case 'AUTO_RENEW_ENABLED':
                        element.subtype_str = '用户已启用订阅自动续订';
                        break;
                    case 'BILLING_RECOVERY':
                        element.subtype_str = '之前续订失败的已过期订阅已成功续订';
                        break;
                    case 'BILLING_RETRY':
                        element.subtype_str = '订阅已过期，因为订阅在计费重试期结束之前未能续订';
                        break;
                    case 'GRACE_PERIOD':
                        element.subtype_str = '由于账单问题，订阅续订失败';
                        break;
                    case 'UPGRADE':
                        element.subtype_str = '用户已升级其订阅或跨级升级到具有相同期限的订阅';
                        break;
                    case 'VOLUNTARY':
                        element.subtype_str = '用户禁用订阅自动续订后订阅已过期';
                        break;
                    case 'DOWNGRADE':
                        element.subtype_str = '用户已降级其订阅或跨级订阅，降级将在下一个续订日期生效。';
                        break;
                }

                // 处理 status
                switch (element.status) {
                    case '1':
                        element.status_str = '自动续订已激活';
                        break;
                    case '2':
                        element.status_str = '自动续订订阅已过期';
                        break;
                    case '3':
                        element.status_str = '自动续订订阅处于计费重试期';
                        break;
                    case '4':
                        element.status_str = '自动续订订阅处于计费宽限期';
                        break;
                    case '5':
                        element.status_str = '自动续订订阅已被撤销';
                        break;
                }

                // 处理 offer_discount_type
                if (element.offer_discount_type == 'FREE_TRIAL') {
                    element.offer_discount_type_str = '免费试用';
                }

                // 处理 consumption_request_reasons
                switch (element.consumption_request_reason) {
                    case 'UNINTENDED_PURCHASE':
                        element.consumption_request_reason_str = '客户无意进行应用内购买。';
                        break;
                    case 'FULFILLMENT_ISSUE':
                        element.consumption_request_reason_str = '客户在接收或使用应用内购买时遇到了问题。';
                        break;
                    case 'UNSATISFIED_WITH_PURCHASE':
                        element.consumption_request_reason_str = '客户对应用内购买不满意。';
                        break;
                    case 'LEGAL':
                        element.consumption_request_reason_str = '客户基于法律原因要求退款。';
                        break;
                    case 'OTHER':
                        element.consumption_request_reason_str = '客户因其他原因要求退款。';
                        break;
                }

                // 处理 revocation_reason
                switch (element.revocation_reason) {
                    case '0':
                        element.revocation_reason_str = 'App Store 因其他原因（例如意外购买）代表客户退还了交易款项。';
                        break;
                    case '1':
                        element.revocation_reason_str = '由于您的应用中存在实际问题或感知问题,App Store 代表客户退还了交易款项。';
                        break;
                }

                // 处理 auto_renew_status
                switch (element.auto_renew_status) {
                    case '0':
                        element.auto_renew_status_str = '关闭';
                        break;
                    case '1':
                        element.auto_renew_status_str = '开启';
                        break;
                }

                // 处理 expiration_intent
                switch (element.expiration_intent) {
                    case '1':
                        element.expiration_intent_str = '用户取消了订阅';
                        break;
                    case '2':
                        element.expiration_intent_str = '由于计费问取消，如信用卡到期或支付失败。';
                        break;
                    case '3':
                        element.expiration_intent_str = '用户从App Store Connect主动取消了订阅。';
                        break;
                    case '4':
                        element.expiration_intent_str = '产品不可用时续订失败';
                        break;
                }
            });
            this.moreArr = data;
            this.total = total;
        },



        handleQuery() {
            this.queryParams.page = 1;
            this.getMore();
        },
        async affirm() {
            this.form.package_name = this.queryParams.package_name;
            this.$refs["ruleForm"].validate(async (valid) => {
                if (!valid) return;
                try {
                    this.addLoading = true;
                    await editFeedbackState(this.form);
                    this.addLoading = false;
                    this.$message.success("操作成功");
                    this.getMore();
                    this.dialogVisible = false;
                } catch (e) {
                    this.addLoading = false;
                }
            });
        },
        openDialog() {
            this.form = {};
            this.dialogVisible = true;
        },
        async handleEdit(i, row) {

            this.form = { ...row };
            this.loading = true;
            let { data, total } = await getHistoryList(this.form);
            this.loading = false;
            data.forEach(element => {
                // 处理 notification_type
                switch (element.notification_type) {
                    case 'SUBSCRIBED':
                        element.notification_type_str = '用户订阅了自动续订';
                        break;
                    case 'CONSUMPTION_REQUEST':
                        element.notification_type_str = '用户发起退款请求';
                        break;
                    case 'DID_CHANGE_RENEWAL_PREF':
                    case 'DID_CHANGE_RENEWAL_STATUS':
                        element.notification_type_str = '用户对订阅计划进行了更改';
                        break;
                    case 'DID_FAIL_TO_RENEW':
                        element.notification_type_str = '用户因账单问题而无法续订，订阅进入账单重试期。';
                        break;
                    case 'DID_RENEW':
                        element.notification_type_str = '用户订阅已成功续订';
                        break;
                    case 'EXPIRED':
                        element.notification_type_str = '用户订阅已过期';
                        break;
                    case 'REFUND':
                        element.notification_type_str = '已成功退款';
                        break;
                    case 'REFUND_DECLINED':
                        element.notification_type_str = 'App Store 拒绝了用户退款请求';
                        break;
                    case 'REFUND_REVERSED':
                        element.notification_type_str = 'App Store 因客户提出的争议而撤销了之前批准的退款';
                        break;
                }

                // 处理 subtype
                switch (element.subtype) {
                    case 'INITIAL_BUY':
                        element.subtype_str = '用户首次订阅成功';
                        break;
                    case 'AUTO_RENEW_DISABLED':
                        element.subtype_str = '用户禁用了订阅自动续订，或者用户申请退款后 App Store 禁用了订阅自动续订';
                        break;
                    case 'AUTO_RENEW_ENABLED':
                        element.subtype_str = '用户已启用订阅自动续订';
                        break;
                    case 'BILLING_RECOVERY':
                        element.subtype_str = '之前续订失败的已过期订阅已成功续订';
                        break;
                    case 'BILLING_RETRY':
                        element.subtype_str = '订阅已过期，因为订阅在计费重试期结束之前未能续订';
                        break;
                    case 'GRACE_PERIOD':
                        element.subtype_str = '由于账单问题，订阅续订失败';
                        break;
                    case 'UPGRADE':
                        element.subtype_str = '用户已升级其订阅或跨级升级到具有相同期限的订阅';
                        break;
                    case 'VOLUNTARY':
                        element.subtype_str = '用户禁用订阅自动续订后订阅已过期';
                        break;
                    case 'DOWNGRADE':
                        element.subtype_str = '用户已降级其订阅或跨级订阅，降级将在下一个续订日期生效。';
                        break;
                }

                // 处理 status
                switch (element.status) {
                    case '1':
                        element.status_str = '自动续订已激活';
                        break;
                    case '2':
                        element.status_str = '自动续订订阅已过期';
                        break;
                    case '3':
                        element.status_str = '自动续订订阅处于计费重试期';
                        break;
                    case '4':
                        element.status_str = '自动续订订阅处于计费宽限期';
                        break;
                    case '5':
                        element.status_str = '自动续订订阅已被撤销';
                        break;
                }

                // 处理 offer_discount_type
                if (element.offer_discount_type == 'FREE_TRIAL') {
                    element.offer_discount_type_str = '免费试用';
                }

                // 处理 consumption_request_reasons
                switch (element.consumption_request_reason) {
                    case 'UNINTENDED_PURCHASE':
                        element.consumption_request_reason_str = '客户无意进行应用内购买。';
                        break;
                    case 'FULFILLMENT_ISSUE':
                        element.consumption_request_reason_str = '客户在接收或使用应用内购买时遇到了问题。';
                        break;
                    case 'UNSATISFIED_WITH_PURCHASE':
                        element.consumption_request_reason_str = '客户对应用内购买不满意。';
                        break;
                    case 'LEGAL':
                        element.consumption_request_reason_str = '客户基于法律原因要求退款。';
                        break;
                    case 'OTHER':
                        element.consumption_request_reason_str = '客户因其他原因要求退款。';
                        break;
                }

                // 处理 revocation_reason
                switch (element.revocation_reason) {
                    case '0':
                        element.revocation_reason_str = 'App Store 因其他原因（例如意外购买）代表客户退还了交易款项。';
                        break;
                    case '1':
                        element.revocation_reason_str = '由于您的应用中存在实际问题或感知问题,App Store 代表客户退还了交易款项。';
                        break;
                }

                // 处理 auto_renew_status
                switch (element.auto_renew_status) {
                    case '0':
                        element.auto_renew_status_str = '关闭';
                        break;
                    case '1':
                        element.auto_renew_status_str = '开启';
                        break;
                }

                // 处理 expiration_intent
                switch (element.expiration_intent) {
                    case '1':
                        element.expiration_intent_str = '用户取消了订阅';
                        break;
                    case '2':
                        element.expiration_intent_str = '由于计费问取消，如信用卡到期或支付失败。';
                        break;
                    case '3':
                        element.expiration_intent_str = '用户从App Store Connect主动取消了订阅。';
                        break;
                    case '4':
                        element.expiration_intent_str = '产品不可用时续订失败';
                        break;
                }
            });
            this.refundList = data
            this.dialogVisible = true;
        },
        handleDelete(index, row) {
            this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "error",
            }).then(async () => {
                await deleteTemplateType({ id: row.id });
                this.getMore();
                this.$message({
                    message: "删除成功！",
                    type: "success",
                });
            });
        },
        resetQuery() {
            this.queryParams.is_agree = null;
            this.queryParams.notification_type = null;
            this.queryParams.pk = null;
            this.queryParams.subtype = null;
            this.queryParams.storefront = null;
            this.queryParams.offer_discount_type = null;
            this.queryParams.package_name = null;
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.queryParams.dateRange2.start = null;
            this.queryParams.dateRange2.end = null;
            this.queryParams.dateRange3.start = null;
            this.queryParams.dateRange3.end = null;
            this.queryParams.page = 1;
            this.value1 = "";
            this.value2 = "";
            this.value3 = "";
            this.getMore();
        },
    },
};
</script>
<style lang="scss" scoped>
.boxs {
    padding: 20px;
}

::v-deep.el-input.is-disabled .el-input__inner {
    color: #333 !important;
}

::v-deep.el-textarea.is-disabled .el-textarea__inner {
    color: #333 !important;
}

::v-deep .el-image {
    margin-right: 8px;
    border-radius: 4px;
}
</style>